<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ShortPollView.ascx.cs"
    Inherits="Controls_ShortPollView" %>

<script language="javascript" type="text/javascript">
    var graphVisible = false;
    
    function showGraph()    {
        var html = '<div id="graphArea">';
        var itemVotes = $F('itemVoteData').split("~");
        var ctr = 0;
        var maxWidth = 96;
        var maxVotes = 0;
        if (itemVotes.length == 0) html += "No Data";
        var itemName = "";
        var votes = 0;
        var graphWidth = 0;
        
        for (ctr = 0; ctr < itemVotes.length; ctr+= 3)  {
            itemName = itemVotes[ctr+1];
            votes = parseInt(itemVotes[ctr+2]);
            if (votes > maxVotes) maxVotes = votes;
            graphWidth = (votes / maxVotes) * maxWidth;
            var spaces = "";
            var i = 0;
            var gbarClass = 'shortPollView-GraphBar';
            if (votes == 0) {
                gbarClass = 'shortPollView-GraphBar-Disabled';
                graphWidth = 1;
            }
            while (i < graphWidth)  {
                spaces += "&nbsp;"; 
                i++;
            }

            html += '<p><span class="' + gbarClass + '" style="width:' + 
                    graphWidth + 'px;">' + spaces + '</span>&nbsp;' + itemName + ' (' + votes + ')</p>';
        }        
        html += "</div>";
        var graphArea = $('graphAreaPlaceHolder');
        graphArea.innerHTML = html;
        graphVisible = true;
    }
    
    function updateItemVotes(itemId, votes) {
        var itemVotes = $F('itemVoteData').split("~");
        if (itemVotes.length == 0)  return;
        for (ctr = 0; ctr < itemVotes.length; ctr+= 3)  {
            if (itemVotes[ctr] == itemId) {
                itemVotes[ctr+2] = votes;
            }
        }
        var newItemData = itemVotes.join("~");
        $('itemVoteData').value = newItemData;
        if(graphVisible)    showGraph();
    }    

    function addVote(itemId) {
        var addVoteResult = function(xmlResult)  {
            if (wsHasErrors(xmlResult))  {
                var errorCode = wsGetErrorCode(xmlResult);
                if (errorCode == wsAlreadyVoted) alert('You have already voted in this poll.');
                if (errorCode == wsUserNameIsNull) {
                    alert('You need to login to vote.');
                    window.location = "/login.aspx?returnToPoll=/PollMain.aspx?id=" + $F('pollId');
                }
            }
            else    {
                var totalVotes = wsGetValueByTag(xmlResult, 'TotalVotes');                        
                var pointsDiv = $("itemPoints-" + itemId);
                pointsDiv.innerHTML = totalVotes;
                var voteLinkDiv = $("itemVoteLink-" + itemId);
                voteLinkDiv.innerHTML = '<span class="grey">Voted</span>';
                updateItemVotes(itemId,totalVotes);
                var canVoteAgain = toBool(wsGetValueByTag(xmlResult, 'CanVoteAgain'));
                if (!canVoteAgain)  {
                    //if we cant vote again remove all the vote links
                    // except the ones for which are 'Voted'
                    var voteLinks =  document.getElementsByClassName('voteLink');
                    for(i = 0; i < voteLinks.length; i++) {
                        if (voteLinks[i].innerHTML.toLowerCase().indexOf("voted") == -1)
                            voteLinks[i].innerHTML = '';
                    }
                }
            }
        }
        var params = {
            itemId: itemId      
        }
        var opt = wsGetStdOptions("Vote", params, addVoteResult, true);
        new Ajax.Request('/PollService.asmx', opt);                       
    }   
    
    function addNewItem()   {
        //requires login       
        if (!isLoggedIn())  {
            alert('You need to login to add an item.');
            window.location = "/login.aspx";
        }
        else    {
            var lbox = new lightbox();
	        lbox.dynamicLoad('/box-AddItem.htm');
        }
    }

    function setItemDetails(itemName, comment, link) {
        if (itemName == '')
        {
            alert('You need to enter a name for the item.');
            return;
        }
        var addItemResult = function (xmlResult)  {
            if (wsHasErrors(xmlResult))  {
                var errorCode = wsGetErrorCode(xmlResult);
                if (errorCode == wsUserNameIsNull) {
                    alert('You need to login to add an item.');
                    window.location = "/login.aspx";
                }
                alert('Error while adding item.');
                return;
            }                     
            alert('Successfully added item.');
            window.location = '/PollMain.aspx?id=' + $F('pollId');
        }
        var params = {
            pollId: $F('pollId'),
            itemName: itemName,
            commentText: comment,
            link: link
        }
        var opt = wsGetStdOptions("AddItem", params, addItemResult, true);
        new Ajax.Request('/PollService.asmx', opt);        
    }
    
    /* COMMENTING */
    var commentedItemNumber = 0;

    function clearCommentedItemNumber() {
        commentedItemNumber = 0;
    }
    
    function addComment(num)   {
        //requires login       
        if (!isLoggedIn())  {
            alert('You need to login to add details.');
            window.location = "/login.aspx";
        }
        else    {
            commentedItemNumber = num; 
            var lbox = new lightbox();
            lbox.dynamicLoad('/box-AddItemComment.htm');        
        }
    }
    
    function setCommentDetails(comment, link)    {
        if (comment == '' && link == '') 
        {
            alert('The comment was empty. Nothing was added.');
            return;
        }
        var addCommentResult = function (xmlResult)  {
            if (wsHasErrors(xmlResult))  {
                var errorCode = wsGetErrorCode(xmlResult);
                if (errorCode == wsUserNameIsNull) {
                    alert('You need to login to add a comment.');
                    window.location = "/login.aspx";
                }
                if (errorCode < 0) alert('Error while adding comment.');
                return;
            }             
            else    {
                alert('Successfully added the comment.');
                var numComments = parseInt($('numComments' + commentedItemNumber).innerHTML);
                var commentsLink = $('commentsLink' + commentedItemNumber);
                commentsLink.innerHTML = 'Comments(' + (numComments + 1) + ')';
            }
        }
        var params = {
            itemId: commentedItemNumber,
            text: comment,
            link: link
        }        
        var opt = wsGetStdOptions("AddComment", params, addCommentResult, true);
        new Ajax.Request('/PollService.asmx', opt);        
    }
    /* --- COMMENTING --- */
    
    function reportIssue()  {
        var lbox = new lightbox();
        lbox.dynamicLoad('/box-ReportIssue.htm');
    }
    
    function logIssue(issues, description)  {
        var issueType = '';
        if(issues[0]){
            for(var i=0;i<issues.length;i++){
                if(issues[i].checked){  issueType = issues[i].value;    }
            }
        } else {
            if(issues.checked) { issueType = issues.value; }
        }
        if(issueType != ''){
            var logIssueResult = function (xmlResult)  {
                if (wsHasErrors(xmlResult))  {
                    var errorCode = wsGetErrorCode(xmlResult);
                }
                if (errorCode > 0){
                    alert("Failed reporting issue. Please try again.");
                } else {
                    alert("The issue has been successfully reported.");
                }
            }
            var params = {
                pollId: $F('pollId'),
                issueType: issueType,
                description: description
            }
            var opt = wsGetStdOptions("LogPollIssue", params, logIssueResult, true);
            new Ajax.Request('/PollService.asmx', opt);
        }
    }
    
    function rateComment(commentId, rating) {
        var rateCommentResult = function (xmlResult)  {
            if (!wsHasErrors(xmlResult))  {
                var rateCommentLink = $('rateCommentLink' + commentId);
                rateCommentLink.innerHTML = '<img src="/Site/Themes/Default/Images/rankUpCommentDim.png" alt="Good Comment" />&nbsp;<img src="/Site/Themes/Default/Images/rankDownCommentDim.png" alt="Bad Comment" />';
            }
        }
        var params = {
            commentId: commentId,
            rating: rating
        }
        var opt = wsGetStdOptions("RateComment", params, rateCommentResult, true);
        new Ajax.Request('/PollService.asmx', opt);
    }
    
    function showAllComments(itemId)  {
        var showAllCommentsResult = function(result) {
            var entries = $A(result.responseXML.getElementsByTagName('GetCommentsResultEntry'));
            var commentsHtml = '';
            entries.each(function(node)    {
                try {
                    var id = wsGetNodeValue(node, 'Id');
                    var text = wsGetNodeValue(node, 'Text');
                    var addedBy = wsGetNodeValue(node, 'AddedBy');
                    var link = wsGetNodeValue(node, 'Link');
                    var rated = toBool(wsGetNodeValue(node, 'UserRated'));
                }   catch(e) {}
                if (text != null && text != '') { 
                    var linkText;    
                    if (link != null && link != '') linkText = '<a href="' + link + '">[More..]</a>';
                    else linkText = '';
                    var rateLinkText = '';
                    //alert(rated);
                    if (rated) {
                        rateLinkText = '<img src="/Site/Themes/Default/Images/rankUpCommentDim.png" />&nbsp;<img src="/Site/Themes/Default/Images/rankDownCommentDim.png" />';
                    } else {
                        rateLinkText = '<span class="linklessLink"><img src="/Site/Themes/Default/Images/rankUpComment.png" onclick="rateComment(' + id + ',1);" />' + 
                            '</span>&nbsp;<span class="linklessLink">' +
                            '<img src="/Site/Themes/Default/Images/rankDownComment.png" onclick="rateComment(' + id + ',-1);" /></span>';
                    }                    
                    
                        commentsHtml +=   '<br /><div class="pollItemComment">' +
                            '<strong><i>' + addedBy + ' says: </i></strong>' + 
                            text + '&nbsp;' + linkText + 
                            '&nbsp;<span id="rateCommentLink' + id + '">' + rateLinkText + '</span><br /></div>';
                }
			});
			$('pollItemComments' + itemId).innerHTML = commentsHtml;
        }
        
        var params = {
            itemId: itemId,
            startRank: 1,
            numComments: 100
        }        
        var opt = wsGetStdOptions("GetComments", params, showAllCommentsResult, true);
        new Ajax.Request('/PollService.asmx', opt);    
    }
</script>

<div class="shortPollViewBox">
    <input id="pollId" name="pollId" value="<%= Poll.Id %>" type="hidden" />
    <input id="itemVoteData" name="itemVoteData" value="<%= GetItemVoteData() %>" type="hidden" />
    <div class="shortPollHeaderBox">
        <div class="pollOptions">
            <% if (!Poll.ItemsLocked)
               { %>
            <span class="linklessLink" onclick="addNewItem();">Add Item</span> |
            <% } %>
            <span class="linklessLink" onclick="showGraph();">Graph</span> | 
            <span class="linklessLink" onclick="reportIssue();">Report Issue</span>
        </div>
        <div class="<%= GetLogoCssClass(Poll.FQCategoryName)%>">
            &nbsp;</div>
        <div class="pollHeader">
            <a href="/PollMain.aspx?id=<%= Poll.Id %>">
                <%= Poll.Title %>
            </a>
        </div>
        <div class="pollDescription">
            <%= Poll.Description %>
        </div>
        <div class="pollLocationInfo">
            <strong>Id: </strong>
            <%= Poll.Id %>
            &nbsp;&nbsp; <strong>In:</strong> <a href="CategoryMain.aspx?name=<%= Poll.FQCategoryName %>">
                <%= Poll.SimpleCategoryName %>
            </a>
        </div>
        <div class="pollStartedBy">
            Started By: <i>
                <%= Poll.StartedBy %>
            </i>
        </div>
    </div>
    <asp:Repeater ID="pollItemsRepeater" runat="server">
        <HeaderTemplate>
            <div id="graphAreaPlaceHolder"></div>
            <div class="pollItems">
        </HeaderTemplate>
        <ItemTemplate>
            <div class="pollItem">
                <div class="pollItemPoints">
                    <div id="itemPoints-<%# DataBinder.Eval(Container.DataItem,"Id") %>">
                        <%# DataBinder.Eval(Container.DataItem,"TotalVotes") %>
                    </div>
                    <span class="pollItemPointsText">votes</span>
                </div>
                <div class="pollItemDetails">
                    <div class="pollItemName">
                        <%# DataBinder.Eval(Container.DataItem,"Name") %>
                    </div>
                    <div id="pollItemComments<%# DataBinder.Eval(Container.DataItem,"Id") %>">
                        <%# GetFormattedComment(((Pervote.Core.PollItem)Container.DataItem).Comment) %>
                    </div>
                    <br />
                    <div class="">
                        <div class="actionsBox">
                            <span class="invisible" id="numComments<%# DataBinder.Eval(Container.DataItem,"Id")  %>">
                                <%# DataBinder.Eval(Container.DataItem, "NumComments") %>
                            </span><span class="linklessLink" id="commentsLink<%# DataBinder.Eval(Container.DataItem,"Id") %>" onclick="showAllComments(<%# DataBinder.Eval(Container.DataItem,"Id") %>);">
                                Comments(<%# DataBinder.Eval(Container.DataItem, "NumComments") %>)</span> |
                            <span class="linklessLink" onclick="addComment(<%# DataBinder.Eval(Container.DataItem,"Id") %>)">
                                Add Comment</span>
                            <br />
                        </div>
                        <div class="voteLink" id="itemVoteLink-<%# DataBinder.Eval(Container.DataItem,"Id") %>"
                            onclick="addVote(<%# DataBinder.Eval(Container.DataItem,"Id") %>)">
                            <%# GetVoteLinkString(((Pervote.Core.PollItem)Container.DataItem).UserVoted) %>
                        </div>
                    </div>
                </div>
            </div>
            <br />
        </ItemTemplate>
        <FooterTemplate>
            </div>
        </FooterTemplate>
    </asp:Repeater>
</div>
